<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<form action="/user/regist" method="post" align="center">
    <h2>注册账号</h2>
    <input type="text" name="username" id="username" >用户名<span id="sp"></span><br>
    <input type="password" name="password">密码<br>
    <input type="text" name="phonenumber">手机号<br>
    <input type="text" name="code">验证码<br>
    <img src="/captcha" style="width: 85px" id="cap">点击切换<br>
    <span id="sp1"></span><br>
    <button type="submit">提交</button>
</form>

<script>

    $(function () {
        $("#cap").click(function () {
            //让img图片重新发送请求，给servlet
            $("#cap").attr('src','/captcha?'+new Date().getTime())
        })
    })




    $(function () {
        $("#username").mouseleave(function () {

            var name = this.value;

            if (name!=null&&name!=""){

                //1.创建Ajax
                var xmlhttp = new XMLHttpRequest();

                //2.设置状态改变监听
                xmlhttp.onreadystatechange = function(){

                    //5获取响应数据
                    if(xmlhttp.readyState == 4 && xmlhttp.status ==200)
                    {
                        var result = xmlhttp.responseText; //获取结果
                        console.log("result为"+result);
                        //  1 行    2 不行
                        //1.找到span标签
                        var sp = document.getElementById("sp1");
                        if(result == 2){
                            //成功的 span 提示一句绿色的话
                            sp.innerHTML="恭喜您!可以注册!!";
                            sp.style.color = "green";
                        }else{
                            //失败的 span 提示一句红色的话
                            sp.innerText="用户已经被注册!";
                            sp.style.color = "red";
                        }
                    }
                    //3.设置ajax method  url
                    xmlhttp.open("POST","/user/exist");
                    //4.发送请求
                    //设置一个请求头
                    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                    xmlhttp.send("username="+name);
                }

            }

        })

    })



</script>


</body>
</html>